package main

import (
	"fmt"
	"sync"
	"time"
)

type share struct {
	mu   sync.Mutex
	name string
}

func (s *share) speed(i int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	fmt.Printf("%d run %s speed begin.. \n", i, s.name)
	time.Sleep(time.Second * 1)
	fmt.Printf("%d run %s speed end.. \n", i, s.name)
}

func (s *share) speedmu(i int) {
	s.mu.Lock()
	fmt.Printf("%d run %s speed begin.. \n", i, s.name)
	s.mu.Unlock()
	time.Sleep(time.Second * 1)
	s.mu.Lock()
	fmt.Printf("%d run %s speed end.. \n", i, s.name)
	s.mu.Unlock()
}

func (s *share) run() {
	s.mu.Lock()
	defer s.mu.Unlock()
	fmt.Printf("create %s\n", s.name)
}
func main() {

	// 测试直接启动goroutune 和 多个那个块
	var wg sync.WaitGroup
	s := &share{name: "test"}

	go func() {
		for {
			time.Sleep(time.Millisecond * 100)
			s.run()
		}
	}()
	t := time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(peer int) {
			s.speed(peer)
			wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Printf("time: %d", time.Since(t))
	fmt.Println("============NEXT=============")

	t = time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(peer int) {
			s.speedmu(peer)
			wg.Done()
		}(i)
	}
	wg.Wait()
	fmt.Printf("time: %d", time.Since(t))
	// 可以剩下1s的时间片处理其他事情
}
